/**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */

import UIKit

//当前视图的高度
private let LSRefreshControlHeight: CGFloat = 50

//MARK: -刷新状态
enum LSRefreshControlType: Int {
    //  下拉刷新
    case Normal = 0
    //  将要刷新
    case Pulling = 1
    //  正在刷新
    case Refreshing = 2
    
}

//MARK: - 自定义下拉刷新控件
class LSRefreshControl: UIControl {
    
    //当前滚动的视图
    var currentScrollView: UIScrollView?
    
    //当前的状态
    var refreshState: LSRefreshControlType = .Normal {
        didSet {
            switch refreshState {
            case .Normal:
                //显示文字为下拉刷新
                messageLabel.text = "下拉刷新"
                //风火轮停止
                indicatorView.stopAnimating()
                //箭头显示，箭头重置
                iconImageView.hidden = false
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformIdentity
                })
                //刷新完成回到默认位置，前提上一次请求是正在刷新状态
                //oldValue 获取上一次的存储的数据是正在刷新然后我们在对contentInset.top减去一个自身的高度
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= LSRefreshControlHeight
                    })
                }
                
            case .Pulling:
                messageLabel.text = "松手就刷新"
                // 下拉箭头调转
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                //显示文字为正在刷新
                messageLabel.text = "正在刷新"
                //下拉箭头隐藏，开启风火轮
                iconImageView.hidden = true
                indicatorView.startAnimating()
                
                //设置停留位置
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    //  一定要记住
                    self.currentScrollView?.contentInset.top += LSRefreshControlHeight
                })
                
                //发送通知(一定要记住)
                sendActionsForControlEvents(.ValueChanged)
                
            }
        }
    }
    
    // MARK:    --懒加载控件
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //MARK: - 风火轮
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    //MARK: - 显示文案
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.blackColor()
        //label.textColor  = UIColor(white: 0.96, alpha: 1)
        label.text = "下拉刷新"
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 添加控件设置约束
    private func setupUI() {

        //backgroundColor = UIColor.redColor()
        backgroundColor = UIColor(white: 0.96, alpha: 1)
        
        //添加控件
        addSubview(iconImageView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        
        //使用系统约束
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
    }
    
    //MARK: - 监听tableview的滚动,拿到tableview, 将控件将要添加到那个父亲视图上
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        //判断父视图是否是可以滚动的视图
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        //代码执行到此是滚动的视图
        
        //设置当前视图的frame
        self.frame.size.width = scrollView.frame.size.width
        self.frame.size.height = LSRefreshControlHeight
        self.frame.origin.y = -LSRefreshControlHeight
        
        //kvo监听滚动对象contentOffSet属性的改变
        //监听contentOffset新值的改变
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        
        //记录滚动的视图
        currentScrollView = scrollView
        
    }
    
    //MARK: - kvo方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        guard let scrollView = currentScrollView else {
            return
        }
        
        //  获取滚动的y轴的偏移量
        let contentOffSetY = scrollView.contentOffset.y
        //  计算临界点
        let maxY = -(scrollView.contentInset.top + LSRefreshControlHeight)
        
        //MARK: - 判断是否在拖动
        if scrollView.dragging {
            
            if contentOffSetY < maxY && refreshState == .Normal {
                //  进入的是将要刷新
                print("pulling")
                refreshState = .Pulling
            } else if contentOffSetY >= maxY && refreshState == .Pulling {
                print("normal")
                refreshState = .Normal
            }
            
        } else {
            
            //判断是否进入正在刷新的状态
            if refreshState == .Pulling {
                //print("refreshing")
                refreshState = .Refreshing
            }
            
        }

    }
    
    //MARK: - 结束刷新
    func endRefreshing() {
        //  进入默认状态
        refreshState = .Normal
    }
    
    deinit {
        //  移除kvo
        currentScrollView?.removeObserver(self, forKeyPath:"contentOffset")
    }
    
}













